<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/8
 * Time: 16:36
 */

namespace App\Http\Logics\MiniProgram;

use App\Cafe;
use App\CafeMappingUser;
use App\City;
use App\Menu;
use App\Partner;
use App\Role;
use App\RoleMappingMenu;
use App\UserFollowCity;
use App\UserMappingCity;
use App\UserMappingPartner;
use App\UserMappingRole;
use App\Users;
use Illuminate\Support\Facades\DB;
use App\Http\Logics\BaseLogic;
class RoleLogic extends BaseLogic
{
    public static function createRole($data)
    {
        try {
            $role = new Role();
            $role->name = $data['name'];
            $role->type = $data['type'];
            if (!$role->save()) {
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function createMiniProgram($data)
    {
        try {
            // 创建事务,创建一个小程序的同时往partner表中插入数据
            DB::transaction(function () use ($data) {
                $role = new Role();
                $role->name = $data['name'];
                $role->type = $data['type'];
                if (!$role->save()) {
                    return self::response(self::OBJECT_DELETE_FAILD);
                }
                $partner = new Partner();
                $partner->role_id = $role->id;
                $partner->app_key = $data['app_key'];
                $partner->appid = $data['appid'];
                $partner->secret = $data['secret'];
                // 为该小程序生成key，并且防止重复
                $flag = true;
                while ($flag){
                    $key = randomStr(10);
                    $partner_two = Partner::where('key', $key)->first();
                    if (empty($partner_two)){
                        $flag = false;
                    }
                }
                $partner->key = $key;
                $partner->name = $data['name'];
                if (!$partner->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
            });
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getMiniProgramList($data)
    {
        try {
            $query = new Role();
            $query = $query->with(['partner'])->where(function ($query) use ($data){
                if (!empty($data['name'])){
                    $query->where('name', 'like', '%' . $data['name'] . '%');
                }
            })->where('type', $data['type'])->orderBy('id', 'desc');
            $role = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($role)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $role);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function deleteMiniProgram($data)
    {
        try {
            $partner = Partner::where('role_id', $data)->first();
            if (empty($partner)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            if (!$partner->delete()){
                return self::response(self::OBJECT_DELETE_FAILD);
            }

            $role = Role::find($data['id']);
            if (!$role->delete()) {
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 删除角色
     * @param $data 筛选条件
     * @return mixed 返回结果
     * @throws \Exception
     */
    public static function deleteRole($data)
    {
        try {
            $role = Role::find($data['id']);
            if (!$role->delete()) {
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getRoleList($data)
    {
        try {
            $query = new Role();
            $query = $query->where('type', $data['type'])->orderBy('sort');
            $role = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
            if (empty($role)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $role);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function setRoleMenu($data)
    {
        try {
            // 创建事务,给用户分配角色的一系列操作并且更新用户角色
            DB::transaction(function () use ($data) {

                RoleMappingMenu::where('role_id', $data['role_id'])->delete();

                $menu_list_arr = explode(',', $data['menu_list']);
                errorLog(is_nan($menu_list_arr[0]));
                if (!is_nan($menu_list_arr[0])) {
                    foreach ($menu_list_arr as $item) {
                        $role_mapping_menu = new RoleMappingMenu();
                        $role_mapping_menu->role_id = $data['role_id'];
                        $role_mapping_menu->menu_id = $item;
                        if (!$role_mapping_menu->save()) {
                            return self::response(self::OBJECT_SAVE_FAIL);
                        }
                    }
                }
            });
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getRoleMenuList($data)
    {
        try {
            $role_mapping_menu = RoleMappingMenu::where('role_id', $data['role_id'])->get();
            if (!empty($role_mapping_menu)) {
                $role_menu_list_arr = [];
                foreach ($role_mapping_menu as $item) {
                    array_push($role_menu_list_arr, $item->menu_id);
                }
            }
            $role_menu_list_string = implode(',', $role_menu_list_arr);
            return self::response(self::SUCCESS, $role_menu_list_string);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getMiniProgramUserMenuList($data)
    {
        $role = Role::with(['menu' => function ($query){
            $query->where('type', Menu::COMMON_MENU);
        }])->find($data['role_id']);
        if (empty($role)) {
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $role);
    }

    /**
     * 获取角色详情
     * @param $data
     * @return mixed
     */
    public static function getRoleDetail($data){
        $role = Role::find($data['role_id']);
        if (empty($role)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $role);
    }

    /**
     * 用户接受城市管理员角色
     * @param $data
     * @return mixed
     */
    public static function setUserCityRole($data)
    {
        try {
            // 创建事务,给用户分配角色的一系列操作并且更新用户角色
            $exception = DB::transaction(function () use ($data) {
                $response = self::getUserIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $user_id = $response->data;

                // 给用户赋予角色
                $user_mapping_role = UserMappingRole::where('user_id', $user_id)->where('role_id', $data['role_id'])->first();
                if (empty($user_mapping_role)) {
                    $user_mapping_role = new UserMappingRole();
                    $user_mapping_role->user_id = $user_id;
                    $user_mapping_role->role_id = $data['role_id'];
                    if (!$user_mapping_role->save()) {
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                }

                $user = Users::find($user_id);
                if (empty($user)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 防止重复授权
                $user_mapping_city = UserMappingCity::where('user_id', $user_id)->where('city_id', $data['city_id'])->first();
                if (!empty($user_mapping_city)){
                    return self::response(self::GET_MANAGER_AGAIN);
                }

                $user_mapping_city = new UserMappingCity();
                $user_mapping_city->user_id = $user_id;
                $user_mapping_city->city_id = $data['city_id'];
                if (!$user_mapping_city->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }

                $city = City::find($data['city_id']);
                if (empty($city)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 组装数据发送邀请通知
                $data_second = [
                    'form_id' => $data['form_id'],
                    'template_id' => 'RAo9c39hmR5b-Rf4wVmIqKzA78UzrRcEDwEfcllx0x4',
                    'touser' => $user->wx_app_openid,
                    'keyword' => [
                        'keyword1' => [
                            'value' => $user->name,
                            'color' => '#000000'
                        ],
                        'keyword2' => [
                            'value' => '接受邀请',
                            'color' => '#000000'
                        ],
                        'keyword3' => [
                            'value' => '请到小程序中管理"'.$city->name.'"吧',
                            'color' => '#000000'
                        ]
                    ],
                    'page' => 'pages/admin/user/home/home'
                ];

                $response = self::getPartnerIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $partner_id = $response->data;
                // 通过loginSession获取AccessToken
                $response = self::getAccessTokenByLoginSession($partner_id);
                if ($response->code) {
                    return self::response($response->code);
                }
                $access_token = $response->data;

                $response = self::createNotify($data_second, $access_token);
                if ($response->code){
                    return self::response($response->code);
                }
            });
            return is_null($exception) ? self::response(self::SUCCESS) : $exception;
        }catch (\Exception $e){
            errorLog($e);
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 用户接收咖啡馆主角色
     * @param $data
     * @return mixed
     */
    public static function setUserCafeRole($data)
    {
        errorLog($data);
        try {
            // 创建事务,给用户分配角色的一系列操作并且更新用户角色
            $exception = DB::transaction(function () use ($data) {
                $response = self::getUserIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $user_id = $response->data;

                // 给用户赋予角色
                $user_mapping_role = UserMappingRole::where('user_id', $user_id)->where('role_id', $data['role_id'])->first();
                if (empty($user_mapping_role)) {
                    $user_mapping_role = new UserMappingRole();
                    $user_mapping_role->user_id = $user_id;
                    $user_mapping_role->role_id = $data['role_id'];
                    if (!$user_mapping_role->save()) {
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                }

                $user = Users::find($user_id);
                if (empty($user)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 防止重复授权
                $cafe_mapping_user = CafeMappingUser::where('user_id', $user_id)->where('cafe_id', $data['cafe_id'])->first();
                if (!empty($cafe_mapping_user)){
                    return self::response(self::GET_MANAGER_AGAIN);
                }

                $cafe_mapping_user = new CafeMappingUser();
                $cafe_mapping_user->user_id = $user_id;
                $cafe_mapping_user->cafe_id = $data['cafe_id'];
                $cafe_mapping_user->is_owner = 1;
                if (!$cafe_mapping_user->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }


                $cafe = Cafe::find($data['cafe_id']);
                if (empty($cafe)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 组装数据发送邀请通知
                $data_second = [
                    'form_id' => $data['form_id'],
                    'template_id' => 'RAo9c39hmR5b-Rf4wVmIqKzA78UzrRcEDwEfcllx0x4',
                    'touser' => $user->wx_app_openid,
                    'keyword' => [
                        'keyword1' => [
                            'value' => $user->name,
                            'color' => '#000000'
                        ],
                        'keyword2' => [
                            'value' => '接受邀请',
                            'color' => '#000000'
                        ],
                        'keyword3' => [
                            'value' => '请到小程序中管理"'.$cafe->name.'"吧',
                            'color' => '#000000'
                        ]
                    ],
                    'page' => 'pages/admin/user/home/home'
                ];
                $response = self::getPartnerIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $partner_id = $response->data;
                // 通过loginSession获取AccessToken
                $response = self::getAccessTokenByLoginSession($partner_id);
                if ($response->code) {
                    return self::response($response->code);
                }
                $access_token = $response->data;

                $response = self::createNotify($data_second, $access_token);
                if ($response->code){
                    return self::response($response->code);
                }
            });
            return is_null($exception) ? self::response(self::SUCCESS) : $exception;
        }catch (\Exception $e){
            errorLog($e);
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function setUserPartnerRole($data)
    {
        try {
            // 创建事务,给用户分配角色的一系列操作并且更新用户角色
            $exception = DB::transaction(function () use ($data) {
                $response = self::getUserIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $user_id = $response->data;

                // 给用户赋予角色
                $user_mapping_role = UserMappingRole::where('user_id', $user_id)->where('role_id', $data['role_id'])->first();
                if (empty($user_mapping_role)) {
                    $user_mapping_role = new UserMappingRole();
                    $user_mapping_role->user_id = $user_id;
                    $user_mapping_role->role_id = $data['role_id'];
                    if (!$user_mapping_role->save()) {
                        return self::response(self::OBJECT_SAVE_FAIL);
                    }
                }

                $user = Users::find($user_id);
                if (empty($user)){
                    return self::response(self::CONTENT_IS_EMPTY);
                }
                $partner = new Partner();
                $partner->name = $data['name'];
                $partner->logo = $data['logo'];
                $partner->summary = $data['summary'];
                $partner->gzh_name = $data['gzh_name'];
                $partner->mobile = $data['mobile'];
                $partner->since = $data['since'];
                if (!$partner->save()){
                    return self::response(self::OBJECT_SAVE_FAIL);
                }

                // 防止重复授权
                $user_mapping_partner = UserMappingPartner::where('user_id', $user_id)->where('partner_id', $partner->id)->first();
                if (!empty($user_mapping_partner)){
                    return self::response(self::GET_MANAGER_AGAIN);
                }

                $user_mapping_partner = new UserMappingPartner();
                $user_mapping_partner->user_id = $user_id;
                $user_mapping_partner->partner_id = $partner->id;
                if (!$user_mapping_partner->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }

                // 组装数据发送邀请通知
                $data_second = [
                    'form_id' => $data['form_id'],
                    'template_id' => 'RAo9c39hmR5b-Rf4wVmIqKzA78UzrRcEDwEfcllx0x4',
                    'touser' => $user->wx_app_openid,
                    'keyword' => [
                        'keyword1' => [
                            'value' => $user->name,
                            'color' => '#000000'
                        ],
                        'keyword2' => [
                            'value' => '接受邀请',
                            'color' => '#000000'
                        ],
                        'keyword3' => [
                            'value' => '请到小程序中管理"'.$partner->name.'"吧',
                            'color' => '#000000'
                        ]
                    ],
                    'page' => 'pages/admin/user/home/home'
                ];

                $response = self::getPartnerIdByLoginSession($data['loginSession']);
                if ($response->code) {
                    return self::response($response->code);
                }
                $partner_id = $response->data;
                // 通过loginSession获取AccessToken
                $response = self::getAccessTokenByLoginSession($partner_id);
                if ($response->code) {
                    return self::response($response->code);
                }
                $access_token = $response->data;

                $response = self::createNotify($data_second, $access_token);
                if ($response->code){
                    return self::response($response->code);
                }
            });
            return is_null($exception) ? self::response(self::SUCCESS) : $exception;
        }catch (\Exception $e){
            errorLog($e);
            return self::response(self::SYSTEM_ERROR);
        }
    }
}